package com.itheima.service;

import com.itheima.mapper.BrandMapper;
import com.itheima.pojo.Brand;
import com.itheima.util.SqlSessionFactoryUtils;
import org.apache.ibatis.session.Configuration;
import org.apache.ibatis.session.SqlSession;
import org.apache.ibatis.session.SqlSessionFactory;

import java.util.List;

public class BrandService {
    //调用SqlSessionFactoryUtils工具类获取sqlSession工厂对象
    SqlSessionFactory sessionFactory = SqlSessionFactoryUtils.getSqlSessionFactory();

    /**
     * 查找表中所有数据
     *调用数据访问层的方法
     * @return
     */
    public List<Brand> selectAll(){
        //获取sqlsession对象
        SqlSession sqlSession = sessionFactory.openSession();
        //获取BrandMapper代理对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用数据访问层的sql方法
        List<Brand> brands = mapper.selectAll();
        //返回数据给表现层中的servlet控制器
        sqlSession.close();
        return brands;

    }


    /**
     * 添加数据
     * @param brand
     * @return
     */
    public int add(Brand brand){
        SqlSession sqlSession = sessionFactory.openSession();

        //获取BrandMapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);

        //调用数据访问层的sql方法
        int add = mapper.add(brand);
        //增删改操作需要提交事务
        sqlSession.commit();

        //关闭资源
        sqlSession.close();
        return add;
    }

    /**
     * 修改数据，首先回显数据(根据id查询数据，因为修改数据是在原来数据的基础上修改的，所以我们要先把数据显示在页面上)，
     * 修改提交后，在插入数据库，然后查询显示数据
     * @param id
     */

    public Brand selectById(int id){
        SqlSession sqlSession = sessionFactory.openSession();

        //获取BrandMapper对象
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        //调用数据访问层的selectById方法
        Brand brand = mapper.selectById(id);
        return brand;
    }

    /**
     * 修改数据
     */
    public void update(Brand brand){
        SqlSession sqlSession = sessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.update(brand);
        sqlSession.commit();
        sqlSession.close();
    }


    /**
     * 根据id删除品牌信息
     */
    public void delete(int id ){
        SqlSession sqlSession = sessionFactory.openSession();
        BrandMapper mapper = sqlSession.getMapper(BrandMapper.class);
        mapper.deleteById(id);
        sqlSession.commit();
        sqlSession.commit();
    }
}
